import { uuid } from "vue-uuid";
import { createStore } from "vuex";
import {setValue} from '../utils/jsonUtil'

export default createStore({
  state: {
    form: {
      col: 1,
      labelPlacement: "top",
      labelWidth: 100,
      size: "medium",
    },
    rules:{},
    fields: [],
    isDel: false,
    i: -1,
  },
  mutations: {
    //表单设置
    setForm(state, value) {
      if (typeof value == "object") {
        for (let key in value) {
          state.form[key] = value[key];
          if (key == "col") {
            state.fields.forEach((item) => {
              if (item.col > value.col) {
                item.col = value.col;
              }
            });
          }
        }
      }
    },
    //设置字段
    setField(state, value) {
      let obj = {
        name: "",
        label: "",
        widget: {
          type: "",
          attr: [
          ],
        },
        id: "",
        row: 1,
        col: 1,
        selected: false,
      };
      if (typeof value == "object" && !state.isDel) {
        for (let key in value) {
          obj[key] = value[key];
        }
        const i = state.fields.findIndex((row) => row == value);
        state.fields[i] = {...obj}
      }
      state.isDel = false;
    },
    //设置控件，配置表单中控件的属性
    setWidget(state, value) {
      if (typeof value == "object") {
        const i = state.fields.findIndex((row) => row.selected == true);
        for (let key in value) {
          state.fields[i].widget[key] = value[key];
        }
      }
    },
    //增加字段
    addField(state, value) {
      let obj = { ...value };
      if (state.fields.findIndex((row) => row == value) >= 0) {
        obj.id = uuid.v4();
      }
      state.fields.push(obj);
    },
    //选中字段
    selectedField(state, value) {
      for (let i = 0; i < state.fields.length; i++) {
        if (state.fields[i].id == value.id) {
          state.fields[i].selected = true;
        } else {
          state.fields[i].selected = false;
        }
      }
    },
    //删除字段
    removeField(state, value) {
      state.isDel = true;
      const i = state.fields.findIndex((row) => row == value);
      if (i == 0 && state.fields.length == 1) {
        state.fields = [];
      } else {
        state.fields.splice(i, 1);
      }
    },
    //移动字段
    moveField(state,value){
      state.isDel = false
      let old = -1
      let obj = {}
      if (value.item == 'selected'){
        old = state.fields.findIndex(row=>row.selected == true)
        obj = {...state.fields[old]}
        if (old>=0){
          state.fields.splice(old,1)
        }
      }else{
        obj = {...value.item}
        if (state.fields.findIndex((row) => row == value) >= 0) {
          obj.id = uuid.v4();
        }
      }
      state.fields.splice(value.index,0,obj)
    },
    //给rules赋值
    setRule(state,value){
      const obj = setValue(value.name.split("\."),value.rule,state.rules)
      Object.assign(state.rules, obj)
    }
  },
  actions: {},
  modules: {},
});
